/**
 * This class is used to parse the GPS data.
 */
package com.pi.parser;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;

import com.pi.tools.GDGPSDataParserUtil;
import com.pi.tools.IGPSDataParserUtil;

/**
 * @author Administrator
 * 
 */
public class GDGpsDataParser {

	public String parseTime(String gpsData) {
		String time = "";
		time += "20" + gpsData.substring(0, 2) + "-"; // 2012-
		time += gpsData.substring(2, 4) + "-"; // 2012-05-
		time += gpsData.substring(4, 6) + " "; // 2012-05-12
		time += gpsData.substring(6, 8) + ":"; // 2012-05-12 13:
		time += gpsData.substring(8, 10) + ":"; // 2012-05-12 13:11
		time += gpsData.substring(10, 12); // 2012-05-12 13:11:34
		return time;
	}

	public void parseFile(String path,String outfileName) throws IOException {
		System.out.println("Enter parseFile");
		IGPSDataParserUtil iGpsUtil = new GDGPSDataParserUtil();
		List<String[]> list = null;
		File infile = new File(path);

		// 判断outfileName是否存在
		File outfile = new File(path + outfileName);
		try {
			if (outfile.exists()) {
				outfile.delete();
				outfile.createNewFile();

			} else {
				outfile.createNewFile();
			}
		} catch (IOException e) {

			e.printStackTrace();
		}
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(new File(path + outfileName));
		} catch (FileNotFoundException e) {

			e.printStackTrace();
		}
		OutputStreamWriter osw = null;
		try {
			osw = new OutputStreamWriter(fos, "UTF-8");
		} catch (UnsupportedEncodingException e) {

			e.printStackTrace();
		}
		BufferedWriter bw = new BufferedWriter(osw);
		if (infile.exists() && infile.list().length > 0) {
			System.out.println("Try to read file");
			String[] filenames = infile.list();
			for (int i = 0; i < filenames.length; i++) {
				if (!filenames[i].equals(outfileName))
					list = iGpsUtil.ParseFile(path + filenames[i]); // 解析GPS数据

				// 向outfile文件写内容
				for (String[] str : list) {
					try {
						bw.write(filenames[i].replace(".txt", "") + ",");
						bw.write(str[0] + ",");
						bw.write(str[1] + ",");
						bw.write(str[2] + ",");
						bw.write(str[3] + ",");
						bw.write(str[4] + ",");
						bw.write(str[5] + ",");
						bw.write(str[6] + ",");
						bw.write(str[7].replace(",", "\\,") + "\r\n");
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			bw.close();
			osw.close();
			fos.close();
		} 
	}
}
